//
//  MVCounterVC.m
//  ConnectorDemo
//
//  Created by huck on 2023/3/24.
//  Copyright © 2023 huck. All rights reserved.
//

#import "MVCounterVC.h"
#import "MyCounterCell.h"

@implementation Counter
-(instancetype)initWithOpen:(NSString *)openPrice close:(NSString*)closePrice lots:(NSString *)lots {
    self = [super init];
    if (self) {
        self.openPrice = openPrice;
        self.closePrice = closePrice;
        self.lots = lots;
    }
    return self;
}
@end
@interface MVCounterVC ()



@end

@implementation MVCounterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"均值计算";
    self.tableView.frame = CGRectMake(0, KStatusNavBarHeight + 84, KScreenWidth, ContentHeight - 84 );
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 220, 0);
    [self.tableView registerNib:[UINib nibWithNibName:@"MyCounterCell" bundle:nil] forCellReuseIdentifier:@"MyCounterCell"];
    
    NSMutableArray *buyList = [NSMutableArray array];
    NSMutableArray *sellList = [NSMutableArray array];
    for (int i=0;i<5;i++) {
        [buyList addObject:[Counter new]];
        [sellList addObject:[Counter new]];
    }
    [self.dataList addObject:buyList];
    [self.dataList addObject:sellList];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.currentPrice.numberKeyboardType  = EBNumberKeyboardTypeDecimal;
}

- (IBAction)counter:(UIButton *)sender {
    [self.view endEditing:YES];
    [self.tableView reloadData];
}

-(void)addLine:(UIButton*)btn{
    Counter *info = [Counter new];
    NSMutableArray *list = self.dataList[btn.tag];
    if (list) {
        [list addObject:info];
        [self.tableView reloadData];
    }
}

#pragma mark - tableView代理 -

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCounterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCounterCell" forIndexPath:indexPath];
    NSArray *list = self.dataList[indexPath.section];
    Counter *counter = list[indexPath.row];
    cell.editFinishBlock = ^(Counter * _Nonnull info) {
        NSMutableArray *listNew = self.dataList[indexPath.section];
        [listNew replaceObjectAtIndex:indexPath.row withObject:info];
    };
    [cell refreshCell:counter row:indexPath currentPrice:self.currentPrice.text];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 60;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView * header = [[[NSBundle mainBundle] loadNibNamed:@"Custom" owner:self options:nil] objectAtIndex:1];
    header.frame = CGRectMake(0, 0, KScreenWidth, 50);
    
    UILabel *lotLabel = [header viewWithTag:1];
    UILabel *priceLabel = [header viewWithTag:2];
    UILabel *pointLabel = [header viewWithTag:3];
    UIButton *addBtn = [header viewWithTag:4];
    addBtn.tag = section;
    [addBtn addTarget:self action:@selector(addLine:) forControlEvents:UIControlEventTouchUpInside];
    
    BOOL buy = section == 0;
    NSArray *list= self.dataList[section];
    
    CGFloat allLots = 0;  //（计算总量，已平仓的除掉）
    CGFloat allPrice = 0; //计算价格，未平仓的,
    CGFloat allCloseProfit = 0; //平仓的获利
    
    for (Counter *info in list) {
        if ([Util isNotEmpty:info.lots] && [Util isNotEmpty:info.openPrice]) {
            CGFloat lots = info.lots.floatValue;
            CGFloat open = info.openPrice.floatValue;
            BOOL hasClose = [Util isNotEmpty:info.closePrice];
            if (hasClose) {
                allCloseProfit += (info.closePrice.floatValue - open) * lots;
            } else {
                allLots += lots;
                allPrice += lots * open;
            }
        }
    }
    CGFloat maPrice = allLots == 0 ? 0 : (allPrice - allCloseProfit) / allLots ; //均价
    lotLabel.text = [Util floatToString:allLots];
    priceLabel.text = [Util floatToString:maPrice];
    
    //计算动态净点数
    CGFloat point = 0;
    if ([Util isEmpty:self.currentPrice.text] || allLots == 0) { //没填现在价，就只能算已经平仓的
        point =  allCloseProfit;
        
    }else { //填了现在价，就一起算
        CGFloat current = self.currentPrice.text.floatValue;
        point = (current - maPrice) * allLots;
    }
    point = buy ? point : point *(-1.0);
    pointLabel.text = [Util floatToString:point];
    pointLabel.textColor = point >= 0 ? [UIColor redColor] : [UIColor greenColor];
    
    return header;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * header = [[[NSBundle mainBundle] loadNibNamed:@"Custom" owner:self options:nil] objectAtIndex:0];
    header.frame = CGRectMake(0, 0, KScreenWidth, 50);
    return header;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSMutableArray *list = self.dataList[indexPath.section] ;
        
        if (indexPath.row < list.count) {
            [list removeObjectAtIndex:indexPath.row];
        }
        
        [self. tableView reloadData];
    }
}



@end
